<template>

  <div class="Priceupdates flex flex-col">
    <!-- 查询区 -->
    <searchCard @onSearch="searchFn" @onReset="resetFn">
      <el-form :model="priceupdatesFrom" label-width="auto" inline @keyup.enter="searchFn">
        <el-form-item label="创建时间：">
          <el-date-picker v-model="value1" type="daterange" range-separator="-" start-placeholder="开始时间"
            end-placeholder="结束时间" @change="timeChangeFn" />
        </el-form-item>
        <el-form-item label="供应商">
          <pb-select v-model="priceupdatesFrom.supplierId" placeholder="请选择供应商" keys="supplierId" label="supplierName"
            :options="PurchaseList" :filterable="true" :filterMethod="filterMethod" />
        </el-form-item>
        <el-form-item label="审核状态：">
          <pb-check :list="classList" @change="changeCheck($event)"></pb-check>
        </el-form-item>
      </el-form>
    </searchCard>

    <!-- 表格区 -->
    <div class="flex-1">
      <pb-card padding="0" height="100%">
        <div class="content-box">
          <ContentOperation>
            <pb-button v-hasPerm="'center:priceupdates:add'" size="small" plain class="mr-6" @click="onaddVisibleFn">
              +添加
            </pb-button>
          </ContentOperation>
          <div class=" main-box ">
            <pb-table :column="planColumn" :tableData="purchasingSupplyData" :bottomElement="['pb-page']"
              :indexWidth="60">
              <template #supplyStatus="{ row }">
                <div class="statusbox">
                  <span class="radius"
                    :style="{ 'background-color': getsupplyStatustextcolorFn(row.supplyStatus, 'color') }"></span><span>{{
                      getsupplyStatustextcolorFn(row.supplyStatus, 'text') }}</span>
                </div>
              </template>
              <template #supplyTenant="{ row }">
                <div class=" flex justify-center ">

                  <el-popover placement="bottom" :width="200" trigger="hover" :content="row.supplyTenant">
                    <template #reference>
                      <div class="popContent pb-ellipsis">
                        {{ row.supplyTenant }}
                      </div>
                    </template>
                  </el-popover>
                </div>
              </template>
              <template #remark="{ row }">
                <div class=" flex justify-center ">

                  <el-popover placement="bottom" :width="200" trigger="hover" :content="row.remark">
                    <template #reference>
                      <div class="popContent pb-ellipsis">
                        {{ row.remark }}
                      </div>
                    </template>
                  </el-popover>
                </div>
              </template>
              <template #operate="{ row }">
                <!-- <pb-button text size="small" @click="offAddpurchaasingFn(row)">启用</pb-button> -->
                <div class="flex">
                  <div v-hasPerm="'center:priceupdates:over'">
                    <PopconfirmButton @confirm="EnableFn(row)" v-if="row.supplyStatus == 0" text="启用">
                    </PopconfirmButton>
                    <PopconfirmButton @confirm="EndbleFn(row)" v-if="row.supplyStatus == 1" text="结束">
                    </PopconfirmButton>
                    <p class="divider mr-2 ml-2" v-if="row.supplyStatus == 0 || row.supplyStatus == 1" text="启用"></p>
                  </div>
                  <div v-hasPerm="'center:priceupdates:view'">
                    <pb-button text size="small" @click="ondetailviewFn(row)">查看</pb-button>
                    <p class="divider mr-2 ml-2"></p>
                  </div>
                  <div v-hasPerm="'center:priceupdates:delete'">
                    <PopconfirmButton v-if="row.supplyStatus != 1" @confirm="deleteFn(row)"></PopconfirmButton>
                    <p class="divider mr-2 ml-2" v-if="row.supplyStatus != 1"></p>
                  </div>
                  <pb-button v-hasPerm="'center:priceupdates:export'" text size="small"
                    @click="offAddpurchaasingFn(row)">导出</pb-button>
                </div>
              </template>
            </pb-table>
            <pb-pagination v-model:currentPage="pages.currentPage" v-model:pageSize="pages.pageSize"
              @onChange="onPagesChange" :total="pages.total"></pb-pagination>
          </div>
        </div>

      </pb-card>
    </div>
    <Viewdetail :isVisible="isVisible" :detailFrom="detailFrom" @offisVisibleFn="offisVisibleFn" />
    <Addprice :addVisible="addVisible" :SupplierList="SupplierList" @canceladdisVisibleFn="canceladdisVisibleFn"
      @confirmaddVisibleFn="confirmaddVisibleFn" />
  </div>
</template>

<script setup lang="ts">
import Viewdetail from './components/viewdetail.vue'
import Addprice from './components/addprice.vue'
import { createMsgBox } from '@/Public-UIlibrary/pb-message-box/method';
import { GetPurchaseSkuSupplyListApi, GetPurchaseListApi, EnablePurchaseSupplyApi, EndPurchaseSupplyApi, DetetePurchaseSupplyApi, ExportSkuSupplyBlodApi } from '@/api/Purchasing'
import { formattedDate } from '@/utils/moment'
const EnableFn = (row: any) => {
  EnablePurchaseSupplyApi({ skuSupplyId: row.skuSupplyId }).then(res => {
    if (res.code == 2000) {
      getPurchaseSkuSupplyListApifn()
    } else if (res.code == 5002) {
      createMsgBox(
        res.msg,
        { cancelText: '取消', showTitleIcon: false, confirmText: '确认', title: '错误提示', Width: 500, connectList: res.data, showIcon: false }).then(res => {
          if (res) {
            // getPurchasePlanApi(1)
          } else {
            // showPopup.value = false
          }
        })
    }
  })
}
const EndbleFn = (row: any) => {
  EndPurchaseSupplyApi({ skuSupplyId: row.skuSupplyId }).then(res => {
    if (res.code == 2000) {
      getPurchaseSkuSupplyListApifn()
    }
  })
}
const deleteFn = (row: any) => {
  DetetePurchaseSupplyApi({ skuSupplyId: row.skuSupplyId }).then(res => {
    if (res.code == 2000) {
      getPurchaseSkuSupplyListApifn()
    }
  })
}
const kitchenList = ref([])
const planColumn = reactive([
  {
    key: 'skuSupplyName',
    name: '供应方案名称'
  },
  {
    key: "supplyCode",
    name: "批次编号",
  },
  {
    key: "supplierName",
    name: "供应商名称",
  },
  {
    key: "createTime",
    name: "创建时间",
  },
  {
    key: 'planUseDate',
    name: "生效时间",
  }, {
    key: 'planEndDate',
    name: "结束时间",
  }, {
    key: 'actualUseDate',
    name: "实际开始时间",
  }, {
    key: 'actualEndDate',
    name: "实际结束时间",
  },
  {
    slot: 'supplyStatus',
    name: "状态",
  }, {
    slot: 'remark',
    name: "备注",
  }, {
    slot: 'supplyTenant',
    name: "供应单位",
  },
  {
    key: 'creator',
    name: '创建人'
  },
  {
    width: 180,
    slot: "operate",
    name: "操作",
    fixed: 'right',
  },
])
const detailFrom = reactive({

})
const PurchaseList = ref([] as any)
const value1 = ref('')
const addpurchaseing = ref(null) as any
const purchasingSupplyData = ref([])
const offAddpurchaasingFn = (row: any) => {
  // console.log('row', row)
  // addpurchaseing.value.showFn(row ? JSON.parse(JSON.stringify(row)) : '')
  ExportSkuSupplyBlodApi({
    skuSupplyId: row.skuSupplyId
  }).then((response: any) => {
    const disposition = response.headers['content-disposition'];
    // const filenameMatch = disposition.match(/filename*=utf-8''\s*([^;]+)/); 没用的东西
    const parts = disposition.split("filename*=utf-8''"); // 注意这里的分割字符串，它包含了一个空的单引号来匹配格式
    const encodedFilenamePart = parts[1] ? parts[1].split(';')[0] : null; // 分割出可能包含文件名的部分，并截取到下一个分号之前
    let decodedFilename = ''
    if (encodedFilenamePart) {
      // 解码文件名
      decodedFilename = decodeURIComponent(encodedFilenamePart);
      decodedFilename = decodedFilename.replace(/\(.*?\)/, '');
      // 输出解码后的文件名
      console.log("Decoded filename:", decodedFilename);
    } else {
      decodedFilename = "物价更新" + new Date().getTime() + '.xlsx'
      // 如果没有找到包含文件名的部分，输出警告信息
      // console.warn("No filename part found in the Content-Disposition header using the simplified method.");
    }
    let blob = new Blob([response.data]);
    let downloadElement = document.createElement("a");
    let href = window.URL.createObjectURL(blob); //创建下载的链接
    // console.log(href, '22href')
    downloadElement.href = href;
    downloadElement.download = decodedFilename; //下载后文件名
    document.body.appendChild(downloadElement);
    downloadElement.click(); //点击下载
    document.body.removeChild(downloadElement); //下载完成移除元素
    window.URL.revokeObjectURL(href); //释放掉blob对象
  })
}
const getsupplyStatustextcolorFn = (status: any, type: string) => {
  if (type == 'text') {
    if (status == 1) {
      return '使用中'
    } else if (status == 2) {
      return '已结束'
    } else {
      return '待生效'
    }
  } else {
    if (status == 1) {
      return '#09B562'
    } else if (status == 2) {
      return 'rgba(0,0,0,0.25)'
    } else {
      return '#F52F3E'
    }
  }
}
const timeChangeFn = (time: any) => {
  // console.log(formattedDate(time[0], 'YYYY-MM-DD'), '22')
  // console.log(formattedDate(time[1], 'YYYY-MM-DD'), '33')
  priceupdatesFrom.startDate = formattedDate(time[0], 'YYYY-MM-DD')
  priceupdatesFrom.endDate = formattedDate(time[1], 'YYYY-MM-DD')
}
const classList = ref([
  { label: '全部', val: null, checked: true },
  { label: '使用中', val: 1, checked: false },
  { label: '已结束', val: 2, checked: false },
  { label: '待生效', val: 0, checked: false },
])
const changeCheck = (eve: any) => {
  // console.log(eve, '22')
  priceupdatesFrom.supplyStatus = eve.val
  getPurchaseSkuSupplyListApifn()
}
const priceupdatesFrom = reactive({
  startDate: "",
  endDate: "",
  supplierId: "",
  supplyStatus: ""
})
const pageInit = () => ({
  total: 0,
  currentPage: 1,
  pageSize: 10,
});
const pages = ref(pageInit());
const onPagesChange = () => {
  getPurchaseSkuSupplyListApifn()
}

const searchFn = () => {
  getPurchaseSkuSupplyListApifn()
}
const resetFn = () => {
  // console.log(value1.value)
  clearObjKey(priceupdatesFrom)
  value1.value = ''
  classList.value.map(el => {
    el.checked = false
  })
  classList.value[0].checked = true
  getPurchaseSkuSupplyListApifn()
}
const getPurchaseSkuSupplyListApifn = () => {
  GetPurchaseSkuSupplyListApi({
    "currentPage": pages.value.currentPage,
    "pageSize": pages.value.pageSize,
    "sortingFields": [
      {
        "field": "",
        "order": ""
      }
    ],
    "startDate": priceupdatesFrom.startDate,
    "endDate": priceupdatesFrom.endDate,
    "supplierId": priceupdatesFrom.supplierId,
    "supplyStatus": priceupdatesFrom.supplyStatus
  }).then(res => {
    purchasingSupplyData.value = res.data.records
    pages.value.total = res.data.total
  })
}
const clearObjKey = (clearForm: any) => {
  Object.keys(clearForm).forEach((key: any) => {
    if (Array.isArray(clearForm[key])) {
      // 如果属性是数组，则清空数组
      clearForm[key].length = 0;
    } else {
      // 如果属性不是数组，则设置为默认值（默认为空字符串）
      clearForm[key] = '';
    }
  });
}
const addVisible = ref(false)
const onaddVisibleFn = () => {
  addVisible.value = true
}
const confirmaddVisibleFn = () => {
  addVisible.value = false
  getPurchaseSkuSupplyListApifn()
}
const canceladdisVisibleFn = () => {
  addVisible.value = false
}
const isVisible = ref(false)
const ondetailviewFn = (row: any) => {
  clearObjKey(detailFrom)
  Object.assign(detailFrom, row)
  isVisible.value = true
}
const offisVisibleFn = () => {
  isVisible.value = false
}
const SupplierList = ref([] as any)
const filterMethod = (query) => {
  if (query) {
    PurchaseList.value = SupplierList.value.filter((item) => {
      return item.supplierId?.toLowerCase().includes(query.toLowerCase()) || item.supplierName?.toLowerCase().includes(query.toLowerCase())
    })
  } else {
    PurchaseList.value = SupplierList.value
  }
}
onMounted(() => {
  getPurchaseSkuSupplyListApifn()
  GetPurchaseListApi({ "pageSize": -1, }).then(res => {
    SupplierList.value = res.data.records
    PurchaseList.value = res.data.records
  })
})
</script>

<style lang="scss" scoped>
.content-box {
  height: 100%;
  display: flex;
  flex-direction: column;
}

.main-box {
  padding: 16px;
  box-sizing: border-box;
}

.Priceupdates {
  .statusbox {
    display: flex;
    align-items: center;

    .radius {
      width: 6px;
      height: 6px;
      // background: red;
      display: inline-block;
      margin-right: 4px;
      border-radius: 10px;
    }
  }
}

.popContent {
  width: 100%;
  overflow: hidden;
}
</style>